<!--
 * @Description:动画匀速封装
 * @Author: Sun
 * @Date: 2019-07-01 20:05:50
 * @LastEditors: Sun
 * @LastEditTime: 2019-07-23 22:40:37
 -->
<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>动画匀速封装</title>
	<style>
		#box {
			width: 100px;
			height: 100px;
			background: pink;
			position: absolute;
			left: 0px;
			top: 50px;
		}

		#box1 {
			width: 100px;
			height: 100px;
			background:paleturquoise;
			position: absolute;
			left: 50px;
			top: 200px;
		}
	</style>
	<script>
		window.onload = function () {
			function $(id) {
				return document.getElementById(id);
			}
			var btn200 = $("btn200")
			var btn400 = $("btn400")
			var box = $("box")
			var box1 = $("box1")
			var timer = null
			btn200.onclick = function () {
				animate(box, 200, 10)
				animate(box1, 260, 6)
			}
			btn400.onclick = function () {
				animate(box, 400, 10)
				animate(box1, 500, 6)
			}
			//封装匀速运动
			function animate(obj, target, speed) {
				clearInterval(obj.timer)
				//物体左边距大于目标距离 - 否则 +
				var speedis = obj.offsetLeft > target ? -speed : speed
				obj.timer = setInterval(() => {
					var result = target - obj.offsetLeft//因为差值不会小于5
					obj.style.left = obj.offsetLeft + speedis + "px"
					if (Math.abs(result) <= speed) { //何时停止 小于步长speed 
						clearInterval(obj.timer)//说明已经到达位置了
						obj.style.left = target + "px"
					}
				}, 30)
			}

			// var arr=[]
			// arr.index=10
			// btn400.onclick = function () {
			// 	animate($("run"), 400)
			// }
		}
	</script>
</head>

<body>
	<button id="btn200">开始200</button>
	<button id="btn400">开始400</button>
	<div id="box"></div>
	<div id="box1"></div>
</body>

</html>